package com.sun.dream.fish.util.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.utility.JavaModule;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.TimeZone;

/**
 * Description:  json转化工具
 * Created By ljl on 2023/12/15.
 */
@Slf4j
public class JsonUtils {
    private static final Object lock = new Object();
    private static volatile ObjectMapper objectMapper;

    public static String toJsonString(Object o) {
        try {
            return getObjectMapper().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("[JsonUtils]异常， ", e);
            return "";
        }
    }

    public static ObjectMapper getObjectMapper() {
        if (objectMapper == null) {
            synchronized (lock) {
                if (objectMapper == null) {
                    objectMapper = createMapper();
                }
            }
        }
        return objectMapper;
    }

    private static ObjectMapper createMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        JavaTimeModule javaModule = new JavaTimeModule();
        javaModule.addSerializer(LocalDateTime.class, new LocalDateTimeJsonSerializer());
        javaModule.addDeserializer(LocalDateTime.class, new LocalDateTimeJsonDeserializer());
        javaModule.addSerializer(LocalDate.class, new LocalDateJsonSerializer());
        javaModule.addDeserializer(LocalDate.class, new LocalDateJsonDeserializer());
        javaModule.addSerializer(LocalTime.class, new LocalTimeJsonSerializer());
        javaModule.addDeserializer(LocalTime.class, new LocalTimeJsonDeserializer());
        objectMapper.registerModule(javaModule);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return objectMapper;
    }

    public static <T> T jsonToClass(String text, Class<T> clazz) {
        try {
            return getObjectMapper().readValue(text, clazz);
        } catch (JsonProcessingException e) {
            log.error("[JsonUtils]异常， ", e);
            return null;
        }
    }
}
